package com.tmt.im.manager.config.beans;

import jakarta.servlet.ServletException;
import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;

import java.io.IOException;
import java.text.MessageFormat;

/**
 * @Description TODO
 * @Author wuyi
 * @Date 2024/7/23 12:20
 * @Version 1.0
 **/
public class MySessionInformationExpiredStrategy implements SessionInformationExpiredStrategy {

    private final OAuth2ClientProperties oAuth2ClientProperties;

    public MySessionInformationExpiredStrategy(OAuth2ClientProperties oAuth2ClientProperties) {
        this.oAuth2ClientProperties = oAuth2ClientProperties;
    }

    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
        String firstProviderName = oAuth2ClientProperties.getProvider().keySet().stream().findFirst().orElse(null);
        String authUrl = oAuth2ClientProperties.getProvider().get(firstProviderName).getAuthorizationUri();
        String baseUrl = authUrl.replace("//", "_").split("/")[0];
        event.getResponse().sendRedirect(MessageFormat.format("{0}/logout", baseUrl));

    }

}
